package cn.iune.erp.customer;

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.Row;
import com.justep.baas.data.RowState;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

import cn.iune.erp.setting.ISettingService;

@Transactional
@Service
public class FileCustomerServiceImpl implements IFileCustomerService {

	@Autowired
	private IFileCustomerDao dao;
	@Autowired
	private IFileCustomerAddressDao detailDao;
	
	@Autowired
	private ISettingService settingService;
	
	@Override
	public void insert(FileCustomer obj) {
		dao.insert(obj);
	}
	
	@Transactional
	@Override
	public void delete(String fID) {
		dao.delete(fID);
	}
	
	@Transactional
	@Override
	public void update(FileCustomer obj) {
		// TODO Auto-generated method stub
		dao.update(obj);
	}	
	
	@Override
	public List<FileCustomer> getAll(){
		return dao.getAll();
	}
	
	@Override
	public FileCustomer getByID(String fID) {
		return dao.getByID(fID);
	}
	
	/*
	@Override
	public FileCustomer getByNo(String customerNo, String enterpriseNo) {
		return dao.getByNo(customerNo, enterpriseNo);
	}
	*/

	@Transactional
	@Override
	public JSONObject save(JSONObject object) throws ParseException  {
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		
		JSONObject data = new JSONObject();
		data.put("concept", table.getTableName());
		JSONArray rows = new JSONArray();
		List<String> idsNew = new ArrayList<String>();
		List<String> idsDel = new ArrayList<String>();
		
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			FileCustomer obj = JSON.toJavaObject(javaObject, FileCustomer.class);
			if(RowState.NEW.equals(obj.getRowState())){
				dao.insert(obj);
				idsNew.add(obj.getfID());
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				dao.delete(obj.getfID());
				idsDel.add(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				FileCustomer objNew = dao.update(obj);
				//返回+1后的version到前台BizData中进行刷新，使得前台的version与后台的一致。
				///////////////////////////////////////////////////////////////////////
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", objNew.getVersion());
				rows.add(jsonRow);
				//////////////////////////////////////////////////////////////////////
			}
		}
		
		data.put("rows", rows);
		data.put("idsNew", idsNew);
		data.put("idsDel", idsDel);
		
		return data;
	}
	
	@Transactional
	@Override
	public JSONObject saveDetail(JSONObject object) throws ParseException {
		// TODO Auto-generated method stub
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		
		JSONObject json = new JSONObject();
		json.put("concept", table.getTableName());
		JSONArray rows = new JSONArray();
		
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			FileCustomerAddress obj = JSON.toJavaObject(javaObject, FileCustomerAddress.class);
			if(RowState.NEW.equals(obj.getRowState())){
				detailDao.insert(obj);
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				detailDao.delete(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				FileCustomerAddress objNew = detailDao.update(obj);
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", objNew.getVersion());
				rows.add(jsonRow);
			}
		}
		
		json.put("rows", rows);
		
		return json;
	}

	
	@Override
	public JSONObject queryUNION(JSONObject data) {
//		return dao.queryUNION(data);
		try {
			JSONObject jsonTable = dao.queryUNION(data);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}
	
	@Override
	public FileCustomer getByOgnID(String ognID, String enterpriseNo) {
		return dao.getByOgnID(ognID, enterpriseNo);
	}
	
	@Override
	public FileCustomer getByLoginName(String sLoginName, String enterpriseNo) {
		return dao.getByLoginName(sLoginName, enterpriseNo);
	}
	

	@Override
	public List<FileCustomer> getList(String enterpriseNo) {
		return dao.getList(enterpriseNo);
	}

	
	@Override
	public FileCustomer getByNo(String customerNo, String enterpriseNo) {
		return dao.getByNo(customerNo, enterpriseNo);
	}
	
	
	@Override
	public FileCustomer getByMemberNo(String memberNo, String enterpriseNo) {
		return dao.getByMemberNo(memberNo, enterpriseNo);
	}
	
	
	@Override
	public FileCustomer getByMobilePhone(String sMobilePhone, String enterpriseNo) {
		return dao.getByMobilePhone(sMobilePhone, enterpriseNo);
	}
	
	@Override
	public FileCustomer getByMobilePhone(String sMobilePhone, int isMember, String enterpriseNo) {
		return dao.getByMobilePhone(sMobilePhone, isMember, enterpriseNo);
	}

	//客户不存在，返回散客代码和随机ID，用于线下交易使用
	@Override
	public FileCustomer getTempGuestInfo() {
		 			
		//这里返回一个临时的
		FileCustomer obj = new FileCustomer();
		
		obj.setfID(Utils.getUUID());
		obj.setStorageTypeD("lsh");
		obj.setStorageTypeDLabel("散客");
		
		obj.setCustomerNo("nonmember");
		obj.setShortName("散客");
		obj.setCustomerName("散客【非会员】");
		
//		obj.setMemberType("GRKH");
//		obj.setMemberTypeLabel("个人客户");
		
		return obj;
	}
	
	

	/*	
	public JSONObject query(JSONObject data) throws Throwable {
		
		// 获取参数
		JSONObject columns = data.getJSONObject("columns"); // 列定义
		String orderBy = data.getString("orderBy"); // 排序
		Integer limit = data.getInteger("limit"); // 分页查询的行数
		Integer offset = data.getInteger("offset"); // 分页查询的行偏移
		String search = data.getString("search"); // 检索关键字
		String filter = data.getString("filter"); // 过滤条件
		String id = data.getString("id");
	
		
		String format = "SELECT %s FROM %s %s %s ";
//		String format = "SELECT ShopCart FROM ShopCart ShopCart %s %s ";
		String select = "FileCustomer";
		String from = "FileCustomer FileCustomer";
		String where = "";

		
		// 存放SQL中的参数值
		List<Object> sqlParams = new ArrayList<Object>();
		// 存放SQL中的过滤条件
		List<String> filters = new ArrayList<String>();
		
		if (!CommonService.isEmptyString(search)) {
			// 增加过滤条件
			filters.add("customerNo LIKE ? OR customerName LIKE ? ");
			// 检索关键字中如果没有%，则前后自动加%
			search = (search.indexOf("%") != -1) ? search : "%" + search + "%";
			// sqlParams的参数个数和顺序必须与过滤条件的?相匹配 
			for (int i = 0; i < 2; i++) {
				sqlParams.add(search);
			}
		}
		
		//处理过滤条件
		if (!CommonService.isEmptyString(filter)) {
			filters.add(filter);
		}
		//处理id
		if (!CommonService.isEmptyString(id)) {
			filters.add("fID='"+id+"'");
		}
	
		
		if(filters != null && filters.size() > 0){
			if(where.indexOf("WHERE")== -1){
				//不包含WHERE关键字
				where = "WHERE " + CommonService.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}else{
				//已包含
				where = where + " AND " + CommonService.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}
		}
		//orderBy = "sortNo ASC";
//		String where = (filters != null && filters.size() > 0) ? " WHERE " + CommonService.arrayJoin(filters.toArray(), "(%s)", " AND ") : "";
		orderBy = !CommonService.isEmptyString(orderBy) ? " ORDER BY " + orderBy : "";
		
		String sql = String.format(format, select, from, where, orderBy);
		System.out.println("sql-->"+sql);
		
		
		//获取数据
		List<Object> list = dao.query(sql,columns,sqlParams,offset,limit);
		
		Table table = Transform.createTableByColumnsDefine(columns);
		List<Row> rows = listToRows(list);

		table.appendRows(rows);
		
		if (offset != null && offset.equals(0)) {
			String sqlTotal = String.format(format, "COUNT(*)", from, where, orderBy);
			long rowCount = dao.getCount(sqlTotal, sqlParams);
			table.setTotal((int)rowCount);
		}
		
		JSONObject json = Transform.tableToJson(table);
	
		return json;
	}
*/
	/*
	public int save(JSONObject object) throws Throwable {
		// TODO Auto-generated method stub
		Table table = Transform.jsonToTable(object);
		List<FileCustomer> list = rowsToList(table.getRows());
		for(FileCustomer obj : list){
			if(RowState.NEW.equals(obj.getRowState())){
				dao.insert(obj);
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				dao.update(obj);
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				dao.delete(obj.getfID());
			}
		}
		return 0;
	}
	
*/	

	/*
	public List<Row> listToRows(List<Object> list){
		//添加行集
		List<Row> rows = new ArrayList<Row>();
		//循环行
	    for(Object o : list){
	    	rows.add(objectToRow(o));
	    }
	    return rows;
	}
	*/
/*
	public List<FileCustomer> rowsToList(List<Row> rows){
		//添加行集
		List<FileCustomer> list = new ArrayList<FileCustomer>();
		//循环行
	    for(Row r : rows){
	    	list.add(rowToObject(r));
	    }
	    return list;
	}
*/
	
	/*
	public Row objectToRow(Object o){
		FileCustomer obj = (FileCustomer) o;
		Map<String, ColumnValue> values = new HashMap<String, ColumnValue>();
		//循环行中每一列
		ColumnValue value = new ColumnValue(obj.getfID());
		values.put("fID", value);
		value = new ColumnValue(obj.getSystemCode());
 		values.put("systemCode", value);
		value = new ColumnValue(obj.getBillType());
 		values.put("billType", value);
		value = new ColumnValue(obj.getBillTypeName());
 		values.put("billTypeName", value);
		value = new ColumnValue(obj.getOrderDate());
 		values.put("orderDate", value);
		value = new ColumnValue(obj.getState());
 		values.put("state", value);
		value = new ColumnValue(obj.getStatus());
 		values.put("status", value);

		value = new ColumnValue(obj.getStorageTypeD());
 		values.put("storageTypeD", value);
		value = new ColumnValue(obj.getStorageTypeDLabel());
 		values.put("storageTypeDLabel", value);
		value = new ColumnValue(obj.getCustomerNo());
 		values.put("customerNo", value);
		value = new ColumnValue(obj.getShortName());
 		values.put("shortName", value);
		value = new ColumnValue(obj.getCustomerName());
 		values.put("customerName", value);

		value = new ColumnValue(obj.getPredictAmount());
 		values.put("predictAmount", value);
		value = new ColumnValue(obj.getInvoiceAmount());
 		values.put("invoiceAmount", value);
		value = new ColumnValue(obj.getAmountL());
 		values.put("amountL", value);

		value = new ColumnValue(obj.getDealDateFirst());
 		values.put("dealDateFirst", value);
		value = new ColumnValue(obj.getDealDateLast());
 		values.put("dealDateLast", value);
		value = new ColumnValue(obj.getAccountBank());
 		values.put("accountBank", value);
		value = new ColumnValue(obj.getAccountNo());
 		values.put("accountNo", value);
		value = new ColumnValue(obj.getTaxNo());
 		values.put("taxNo", value);

		value = new ColumnValue(obj.getInvoiceCategory());
 		values.put("invoiceCategory", value);
		value = new ColumnValue(obj.getInvoiceCategoryLabel());
 		values.put("invoiceCategoryLabel", value);
 		
		value = new ColumnValue(obj.getTaxType());
 		values.put("taxType", value);
		value = new ColumnValue(obj.getTaxTypeLabel());
 		values.put("taxTypeLabel", value);
		value = new ColumnValue(obj.getTaxRate());
 		values.put("taxRate", value);

		value = new ColumnValue(obj.getDepositRate());
 		values.put("depositRate", value);

		value = new ColumnValue(obj.getSettleCategory());
 		values.put("settleCategory", value);
		value = new ColumnValue(obj.getSettleCategoryLabel());
 		values.put("settleCategoryLabel", value);
 		
		value = new ColumnValue(obj.getsIDCard());
 		values.put("sIDCard", value);
		value = new ColumnValue(obj.getsLoginName());
 		values.put("sLoginName", value);
		value = new ColumnValue(obj.getsPassword());
 		values.put("sPassword", value);
		value = new ColumnValue(obj.getsPasswordTimeLimit());
 		values.put("sPasswordTimeLimit", value);
		value = new ColumnValue(obj.getsPasswordModifyTime());
 		values.put("sPasswordModifyTime", value);
 		
		value = new ColumnValue(obj.getRegisterDate());
 		values.put("registerDate", value);
		value = new ColumnValue(obj.getValidataCode());
 		values.put("validataCode", value);

		value = new ColumnValue(obj.getsOfficeAddress());
 		values.put("sOfficeAddress", value);
		value = new ColumnValue(obj.getsZip());
 		values.put("sZip", value);
		value = new ColumnValue(obj.getsMail());
 		values.put("sMail", value);
		value = new ColumnValue(obj.getsMailState());
 		values.put("sMailState", value);
		value = new ColumnValue(obj.getsOfficePhone());
 		values.put("sOfficePhone", value);

		value = new ColumnValue(obj.getGroupID());
 		values.put("groupID", value);
		value = new ColumnValue(obj.getGroupCode());
 		values.put("groupCode", value);
		value = new ColumnValue(obj.getGroupName());
 		values.put("groupName", value);
		value = new ColumnValue(obj.getGroupFullName());
 		values.put("groupFullName", value);
		value = new ColumnValue(obj.getRegionID());
 		values.put("regionID", value);
		value = new ColumnValue(obj.getRegionCode());
 		values.put("regionCode", value);
		value = new ColumnValue(obj.getRegionName());
 		values.put("regionName", value);
		value = new ColumnValue(obj.getRegionFullName());
 		values.put("regionFullName", value);
		
		value = new ColumnValue(obj.getComments());
 		values.put("comments", value);

		value = new ColumnValue(obj.getcUsercode());
 		values.put("cUsercode", value);
		value = new ColumnValue(obj.getcUsername());
 		values.put("cUsername", value);
		value = new ColumnValue(obj.getcDatetime());
 		values.put("cDatetime", value);
		value = new ColumnValue(obj.gettUsercode());
 		values.put("tUsercode", value);
		value = new ColumnValue(obj.gettUsername());
 		values.put("tUsername", value);
		value = new ColumnValue(obj.gettDatetime());
 		values.put("tDatetime", value);
		value = new ColumnValue(obj.geteUsercode());
 		values.put("eUsercode", value);
		value = new ColumnValue(obj.geteUsername());
 		values.put("eUsername", value);
		value = new ColumnValue(obj.geteDatetime());
 		values.put("eDatetime", value);

		value = new ColumnValue(obj.getUserId());
 		values.put("userId", value);
		value = new ColumnValue(obj.getEnterpriseNo());
 		values.put("enterpriseNo", value);
		value = new ColumnValue(obj.getEnterpriseName());
 		values.put("enterpriseName", value);

		value = new ColumnValue(obj.getVersion());
 		values.put("version", value);
		
		Row row = new Row(values,RowState.NONE);
		return row;
	}
	*/
	/*	
	public FileCustomer rowToObject(Row row){
		FileCustomer obj = new FileCustomer();
		obj.setfID(row.getString("fID"));
	    
		obj.setSystemCode(row.getString("systemCode"));			
		obj.setBillType(row.getString("billType"));
		obj.setBillTypeName(row.getString("billTypeName"));
		obj.setOrderDate(row.getDate("orderDate"));
		obj.setState(row.getString("state"));
		obj.setStatus(row.getString("status"));

		obj.setStorageTypeD(row.getString("storageTypeD"));
		obj.setStorageTypeDLabel(row.getString("storageTypeDLabel"));
		obj.setCustomerNo(row.getString("customerNo"));
		obj.setShortName(row.getString("shortName"));
		obj.setCustomerName(row.getString("customerName"));
		
		obj.setPredictAmount(row.getDecimal("predictAmount"));
		obj.setInvoiceAmount(row.getDecimal("invoiceAmount"));
		obj.setAmountL(row.getDecimal("amountL"));
		
		obj.setDealDateFirst(row.getDate("dealDateFirst"));
		obj.setDealDateLast(row.getDate("dealDateLast"));
		
		obj.setAccountBank(row.getString("accountBank"));
		obj.setAccountNo(row.getString("accountNo"));
		obj.setTaxNo(row.getString("taxNo"));
		obj.setInvoiceCategory(row.getString("invoiceCategory"));
		obj.setInvoiceCategoryLabel(row.getString("invoiceCategoryLabel"));
		
		obj.setTaxType(row.getInteger("taxType"));
		obj.setTaxTypeLabel(row.getString("taxTypeLabel"));
		obj.setTaxRate(row.getDecimal("taxRate"));
		
		obj.setDepositRate(row.getDecimal("depositRate"));
		
		obj.setSettleCategory(row.getString("settleCategory"));
		obj.setSettleCategoryLabel(row.getString("settleCategoryLabel"));
		
		obj.setGroupID(row.getString("groupID"));
		obj.setGroupCode(row.getString("groupCode"));
		obj.setGroupName(row.getString("groupName"));
		obj.setGroupFullName(row.getString("groupFullName"));
		obj.setRegionID(row.getString("regionID"));
		obj.setRegionCode(row.getString("regionCode"));
		obj.setRegionName(row.getString("regionName"));
		obj.setRegionFullName(row.getString("regionFullName"));
	
		obj.setComments(row.getString("comments"));

		obj.setcUsercode(row.getString("cUsercode"));
		obj.setcUsername(row.getString("cUsername"));
		obj.setcDatetime(row.getDateTime("cDatetime"));
		obj.settUsercode(row.getString("tUsercode"));
		obj.settUsername(row.getString("tUsername"));
		obj.settDatetime(row.getDateTime("tDatetime"));
		obj.seteUsercode(row.getString("eUsercode"));
		obj.seteUsername(row.getString("eUsername"));
		obj.seteDatetime(row.getDateTime("eDatetime"));
		
		obj.setUserId(row.getString("userId"));

		obj.setEnterpriseNo(row.getString("enterpriseNo"));
		obj.setEnterpriseName(row.getString("enterpriseName"));
		
		obj.setVersion(row.getInteger("version"));
		
		obj.setRowState(row.getState());

		return obj;
	}
*/


	@Override
	public FileCustomer packing(
			String billType
			,String billTypeName 
			,String systemCode 
//			,int flowType 
//			,String revOpay 
//			,int direction 
//			,String costingCode 
			,String autoCode 
//			,String origin 
//			,String originName 
			,String billNo 
			
			,String cUsercode,String cUsername,String userId,String enterpriseNo,String enterpriseName){
		
		FileCustomer obj = new FileCustomer();
		String fID = Utils.getUUID();
		obj.setfID(fID);
		//单号
		/*
		Map<String,Object> map = usercenterService.getBillParam(billType, enterpriseNo);
		String billTypeName = (String) map.get("billTypeName");
		String systemCode = (String) map.get("systemCode");
//		String autoCode = (String) map.get("autoCode");
//		if("Y".equals(autoCode)){
//			String billNo = (String) map.get("billNo");
//			obj.setCustomerNo(billNo);
//		}
		*/
		obj.setCustomerNo(billNo);
		
		obj.setBillType(billType);
		obj.setBillTypeName(billTypeName);
		obj.setSystemCode(systemCode);
		
		obj.setState("active");
		obj.setStatus("open");
		obj.setOrderDate(Utils.getCurrentDate());
		
		obj.setStorageTypeD("cus");
		obj.setStorageTypeDLabel("客户档案");
		
		obj.setInvoiceCategory("D");
		obj.setInvoiceCategoryLabel("D.其他");
		obj.setSettleCategory("8");
		obj.setSettleCategoryLabel("8.货到付款");
		obj.setTaxType(1);
		obj.setTaxTypeLabel("1.应税内含");
		obj.setTaxRate(BigDecimal.ZERO);
		
		obj.setDepositRate(BigDecimal.ZERO);
		
//		obj.setMemberAmount(BigDecimal.ZERO);
//		obj.setAllocatedAmount(BigDecimal.ZERO);
		
//		obj.setComments();
		
		obj.setcUsercode(cUsercode);
		obj.setcUsername(cUsername);
		obj.setcDatetime(Utils.getCurrentDateTime());
		obj.setUserId(userId);
		obj.setEnterpriseNo(enterpriseNo);
		obj.setEnterpriseName(enterpriseName);
		
		obj.setVersion(0);
		
		return obj;
		
				
	}

	//创建非会员记录（这个应该不再使用）
	@Transactional
	@Override
	public FileCustomer creatNonmember(String cUsercode,String cUsername,String userId,String enterpriseNo,String enterpriseName){
		
//		FileCustomer fileCustomer = this.packing("KHDA", cUsercode, cUsername, userId, enterpriseNo, enterpriseName);
		String billType = "KHDA";
		String billTypeName = "客户档案";
		String systemCode = null;
		String autoCode = "N";
		String billNo = null;

		FileCustomer fileCustomer = this.packing(billType, billTypeName, systemCode, autoCode, billNo, cUsercode, cUsername, userId, enterpriseNo, enterpriseName);
		
		//新建客户档案，用于门店的会员沉淀
//		fileCustomer.setStorageTypeD("psn");
//		fileCustomer.setStorageTypeDLabel("个人");		
		fileCustomer.setStorageTypeD("cus");
		fileCustomer.setStorageTypeDLabel("客户");
		
		fileCustomer.setMemberType("GRKH");
		fileCustomer.setMemberTypeLabel("个人客户");
		
		fileCustomer.setCustomerNo("nonmember");
		fileCustomer.setShortName("非会员");
		fileCustomer.setCustomerName("非会员");
		
//		fileCustomer.setsMobilePhone();
//		fileCustomer.setsPhone();
		
		dao.insert(fileCustomer);
		
		return fileCustomer;
	}

	//交易时自动创建会员记录
	@Transactional
	@Override
	public FileCustomer creatAutomember(String sLoginName, String sMobilePhone, String personID, String personCode, String personName, String cUsercode,String cUsername,String userId,String enterpriseNo,String enterpriseName){
		
//		FileCustomer fileCustomer = this.packing("KHDA", cUsercode, cUsername, userId, enterpriseNo, enterpriseName);
		String billType = "KHDA";
		String billTypeName = "客户档案";
		String systemCode = null;
		String autoCode = "N";
		String billNo = settingService.getMaxCode(billType, enterpriseNo);

		FileCustomer fileCustomer = this.packing(billType, billTypeName, systemCode, autoCode, billNo, cUsercode, cUsername, userId, enterpriseNo, enterpriseName);
		
		//新建客户档案，用于门店的客户沉淀
		fileCustomer.setStorageTypeD("cus");
		fileCustomer.setStorageTypeDLabel("客户");
		
		fileCustomer.setMemberType("GRKH");
		fileCustomer.setMemberTypeLabel("个人客户");
		//fileCustomer.setCustomerNo(personCode);
		String shortName = null;
		String customerName = null;
		if(personName!=null && !"".equals(personName)) {
			if(personName.length()>=4) {
				shortName = personName.substring(0, 4);
			}else {
				shortName = personName;
			}
			customerName = personName + personCode;
		}else {
			customerName = personCode;
		}
		fileCustomer.setShortName(shortName);
		fileCustomer.setCustomerName(customerName);
		
		fileCustomer.setsMobilePhone(sMobilePhone);
//		fileCustomer.setsPhone();
		
		fileCustomer.setsLoginName(sLoginName);
		fileCustomer.setOgnID(personID);
		
		fileCustomer.setIsMember(1);
		String memberNo = String.valueOf(System.nanoTime());
		fileCustomer.setMemberNo(memberNo);
		
		dao.insert(fileCustomer);
		
		return fileCustomer;
	}
	
	//更新初次交易时间
	@Transactional
	@Override
	public int updateDealDateFirst(FileCustomer fc, Date dealDate) {
		fc.setDealDateFirst(dealDate);
		dao.update(fc);
		return 0;
	}

	//更新最近交易时间
	@Transactional
	@Override
	public int updateDealDateLast(FileCustomer fc, Date dealDate) {
		fc.setDealDateLast(dealDate);
		//首先判断是否初次交易
		if (fc.getDealDateFirst()==null){
			//初次交易
			//更新初次交易时间
			fc.setDealDateFirst(dealDate);
		}
		dao.update(fc);
		return 0;
	}


	//更新会员余额
	@Transactional
	@Override
	public FileCustomer updateMemberAmount(String fID, BigDecimal memberAmount) {
		FileCustomer fc = this.getByID(fID);
		if(fc!=null){
			fc.setMemberAmount(fc.getMemberAmount().add(memberAmount));
			return dao.update(fc);
		}else{
			return null;
		}
	}

	//更新消费积分
	@Transactional
	@Override
	public int updateMemberPoints(FileCustomer fc, BigDecimal memberPoints) {
		fc.setMemberPoints(fc.getMemberPoints().add(memberPoints));
		dao.update(fc);
		return 0;
	}



	//更新消费积分
	@Transactional
	@Override
	public int updateMemberPoints(String fID, BigDecimal memberPoints) {
		FileCustomer fc = this.getByID(fID);
		if(fc!=null){
			this.updateMemberPoints(fc, memberPoints);
		}else{
			return -1;
		}
		return 0;
	}

	
	//获取会员余额
	@Override
	public JSONObject getMemberAmount(String fID) {
		JSONObject json = new JSONObject();
		
		FileCustomer fc = this.getByID(fID);
		if(fc!=null){
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", fc.getMemberAmount());
			return json;
		}else{
			json.put("code", -1);
			json.put("msg", "failure");
			json.put("info", "会员不存在！");
			return json;
		}
	}
	
	@Override
	public void beforeInsert(FileCustomer obj) {
		
		if(obj.getCustomerNo()==null){
			//编号为null，产生编号
			String billType = obj.getBillType();
			String enterpriseNo = obj.getEnterpriseNo();
			String customerNo = settingService.getMaxCode(billType, enterpriseNo);
			obj.setCustomerNo(customerNo);
			
		}else{
			//判断是否为空格
			String customerNo = obj.getCustomerNo().trim();
			if("".equals(customerNo)){
				//编号为""，产生编号
				String billType = obj.getBillType();
				String enterpriseNo = obj.getEnterpriseNo();
				customerNo = settingService.getMaxCode(billType, enterpriseNo);
				obj.setCustomerNo(customerNo);
				
			}else{
				//去掉空格后赋值
				obj.setCustomerNo(customerNo);
			}
		}
		
	}
	
	@Override
	public void afterInsert(FileCustomer obj) {
		
	}

	@Override
	public void beforeDelete(String fID) {
		
	}
	
	@Override
	public JSONObject newData(JSONObject data) {
		return dao.create(data);
	}
	
	@Override
	public JSONObject deleteData(JSONObject param) {
		
		JSONArray ids = param.getJSONArray("ids");
		for(int i=0;i<ids.size();i++){
			String id = ids.getString(i);
			//这里可以增加是否可删除的判断
			
			//首先删除子表
			List<FileCustomerAddress> sods = detailDao.getByMasterID(id);
			for(FileCustomerAddress sod:sods){
				detailDao.delete(sod.getfID());
			}

			//然后删除主表
			dao.delete(id);
		}

		JSONObject data = new JSONObject();
		data.put("ids", ids);
		
		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("msg", "success");
		json.put("data", data);
		
		return json;
	}
	
	@Override
	public JSONObject saveData(JSONObject param) {
		// TODO Auto-generated method stub
		JSONObject data;
		try {
			//保存主表
			data = this.save(param);
			
			//保存从表
			JSONArray slaves = param.getJSONArray("slaves");
			JSONObject slaveParam = slaves.getJSONObject(0);
			
			JSONObject slaveData = this.saveDetail(slaveParam);
			
			JSONArray slaveDatas = new JSONArray();
			slaveDatas.add(slaveData);
			data.put("slaves", slaveDatas);
					
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", data);
			
			return json;
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			
			return json;
		} 
	}
	
	@Override
	public JSONObject queryData(JSONObject param) {
		// TODO Auto-generated method stub
		try {
			JSONObject jsonTable = dao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}
	
	@Override
	public JSONObject validData(JSONObject param) {
		// TODO Auto-generated method stub
		return null;
	}

	//新增子表
	@Override
	public JSONObject newDataDetail(JSONObject data) {
		return detailDao.create(data);
	}
	
	//查询子表
	@Override
	public JSONObject queryDataDetail(JSONObject param) {
		// TODO Auto-generated method stub
		try {
			JSONObject jsonTable = detailDao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}


	

}
